<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/5/25
 * Time: 下午2:17
 */
use think\Route;

header('Access-Control-Allow-Origin:*');
if(request()->isOptions()){
    header('content-type:application:json;charset=utf8');
    header('Access-Control-Allow-Origin:*');
    header('Access-Control-Allow-Headers:x-requested-with,content-type,Authorization');
    exit;
}

// 设置模型命名空间前缀
config('mogosdk.namespace_prefix','demo');
// 设置api接口前缀
$api_prefix = 'mogo-sdk';
/**
 * 查询列表
 */
Route::post('mogo-sdk/class/:class$',function($class){
    $q = request()->post();
    $namespace_prefix = config('mogosdk.namespace_prefix');
    // 判断类存在
    try{
        $Model = model("{$namespace_prefix}/{$class}");
    }catch (Exception $exception){
        return json(['message'=>'Class not find','code'=>__LINE__],404);
    }
    //TODO 判断类允许查询
    // 处理排序
    $order = isset($q['order'])?$q['order']:'id desc';
    // 处理查询
    $where = isset($q['where'])?whereHandle($q['where']):[];;
    //TODO 处理时间查询
    // 处理关联
    $with = isset($q['with'])?$q['with']:[];
    $withCount = isset($q['withCount'])?$q['withCount']:[];
    // 处理条数
    $limit = isset($q['limit'])?$q['limit']:10;
    try{
        $res= $Model
            ->where($where)
            ->order($order)
            ->with($with)
            ->withCount($withCount)
            ->paginate($limit)->each(function($item){
                // 处理额外字段
                $q = request()->post();
                if(isset($q['attr']))  $attr = $q['attr'];
                else $attr=[];
                foreach ($attr as $value){
                    $item[$value]  =  $item->getAttr($value);
                }
            });
    }catch (Exception $exception){
        return json(['message'=>$exception->getMessage(),'code'=>__LINE__],502);
    }
    return json($res);
});
/**
 * 查询单个
 */
Route::post('mogo-sdk/class/:class/:id$',function($class,$id){
    $q = request()->post();
    $namespace_prefix = config('mogosdk.namespace_prefix');
    // 判断类存在
    try{
        $Model = model("{$namespace_prefix}/{$class}");
    }catch (Exception $exception){
        return json(['message'=>'Class not find','code'=>__LINE__],404);
    }
    //TODO 处理时间查询
    // 处理关联
    $with = isset($q['with'])?$q['with']:[];
    // 处理关联统计
    $withCount = isset($q['withCount'])?$q['withCount']:[];
    // 处理条数
    $attr =  isset($q['attr'])?$q['attr']:[];
    try{
        $res= $Model
            ->where('id',$id)
            ->with($with)
            ->withCount($withCount)
            ->find();
        if(!$res) return mogo_error('资源不存在');
        foreach ($attr as $value){
            $res[$value] = $res->getAttr($value);
        }
    }catch (Exception $exception){
        return json(['message'=>$exception->getMessage(),'code'=>__LINE__],502);
    }
    return json($res);
});
/**
 * 执行模型中public函数
 */
Route::post('mogo-sdk/:class/method/:method$',function($class,$method){
    $namespace_prefix = config('mogosdk.namespace_prefix');
    // 判断类存在
    try{
        $Model = model("{$namespace_prefix}/{$class}");
    }catch (Exception $exception){
        return json(['message'=>'Class permission or Class not find','extra'=>$exception,'code'=>__LINE__],404);
    }
    // 判断方法存不存在
    if(!method_exists($Model,$method)) return mogo_error('method permission or method not find');
    // 安全过滤 过滤掉think 的模型自带的方法 如create
    $permission = get_class_methods($Model);
    $permission_index =  array_search('__construct',$permission);
    $method_index =  array_search($method,$permission);
    if($method_index>=$permission_index) return json(['error'=>'method permission or method not find','code'=>__LINE__],404);

    $res = call_user_func(array($Model, $method));
    return $res;
});

// 处理where参数
function whereHandle($where){
    foreach ($where as &$value){
        $value[0] = trim($value[0]);
        // 将模糊查询直接注入
        if($value[0]=='like') $value[1] = "%{$value[1]}%";
    }
    return $where;
}

// 处理关联参数
function withHandle($with){
    return $with;
}